//
//  XJLSearchResultViewController.m
//  XJL_WeChat
//
//  Created by XJL on 16/8/2.
//  Copyright © 2016年 Xujiali. All rights reserved.
//

#import "XJLSearchResultViewController.h"

@interface XJLSearchResultViewController ()
/** 搜索的结果*/
@property(nonatomic,strong) NSMutableArray *searchResult;
@end

@implementation XJLSearchResultViewController

-(NSMutableArray *)searchResult{
    if (_searchResult == nil) {
        _searchResult = [NSMutableArray array];
    }
    return _searchResult;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.searchResult = [NSMutableArray array];
}

#pragma mark 监听搜索条内容的改变
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    // 实际开发,搜索功能的实现
    // 1.把关键字(searchbar的内容)发一个请求给服务
    // 2.环信没有提供搜索好友的接口
//    XJLLog(@"%@",searchController.searchBar.text);
    //实现假搜索
    [self.searchResult removeAllObjects];
    [self.searchResult addObject:searchController.searchBar.text];
    [self.tableView reloadData];
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

//    XJLLog(@"%ld",self.searchResult.count);
    return self.searchResult.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if(cell == nil){
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.backgroundColor = [UIColor grayColor];
        [btn setTitle:@"添加" forState:UIControlStateNormal];
        [btn sizeToFit];
        [btn addTarget:self action:@selector(addFriend:) forControlEvents:UIControlEventTouchUpInside];
        cell.accessoryView = btn;
    }
    
    //取出btn
    UIButton *btn = (UIButton *)cell.accessoryView;
    btn.tag = indexPath.row;
    cell.textLabel.text = self.searchResult[indexPath.row];
    
    return cell;
}

//#warning 添加好友。。。
-(void)addFriend:(UIButton *)btn {

    //加好友
    //获取好友的名称
    NSString *buddy = self.searchResult[btn.tag];
    NSString *msg = @"你好，我是你同学";
    //发送网络请求
    EMError *error = nil;
    [[EaseMob sharedInstance].chatManager addBuddy:buddy message:msg error:&error];
    XJLLog(@"%@,%@",buddy,msg);
    if (!error) {
        [SVProgressHUD showSuccessWithStatus:@"添加好友的请求发送成功"];
    }else{
        [SVProgressHUD showErrorWithStatus:@"添加好友的请求发送失败"];
    }
}

@end
